﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace QQ2564874169.Core.ORM
{
    public class EntityContext
    {
        public Type Type { get; internal set; }
        public string SqlName { get; internal set; }
        public IDictionary<string, object> Paramters { get; } = new Dictionary<string, object>();

        public static EntityContext Parse(Type type, object model)
        {
            var ctx = new EntityContext
            {
                Type = type,
                SqlName = type.Name
            };
            var attr = type.GetCustomAttribute<DbNameAttribute>();
            if (attr != null)
            {
                ctx.SqlName = attr.Name;
            }
            var ps = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);

            foreach (var p in ps)
            {
                var v = p.GetValue(model);
                if (v != null)
                {
                    var cattr = p.GetCustomAttribute<DbNameAttribute>();
                    ctx.Paramters.Add(cattr != null ? cattr.Name : p.Name, v);
                }
            }

            return ctx;
        }
    }
}
